import React, { Component } from 'react'
import { Form, Radio, Checkbox, Row, Col, Button, Spin, message } from 'antd'
import { messages } from "share/common";
import AssignCompany from 'containers/setting/allocate-center/template/assign-company'
import AllocateServices from 'containers/setting/allocate-center/allocate-services'
const { Item } = Form;
const { Group } = Checkbox;
const RadioGroup = Radio.Group;
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 14 },
};

class AddDesk extends Component {
  state = {
    record: {},
    scope: 'BOOKS',
    rangeOptions: [
      { label: messages('setting.key2147')/*全帐套*/, value: 'BOOKS' },
      { label: messages('setting.key1229')/*部分*/, value: 'COMPANY' }
    ],
    loading: false,
    saveLoading: false,
    extraForm: [],
    assignCompanies: []
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.showSlideFrame === this.props.showSlideFrame)
      return;
    if (!nextProps.showSlideFrame) {
      this.props.form.resetFields();
      this.setState({ assignCompanies: [], scope: 'BOOKS' });
      return !1;
    }
    this.props.form.resetFields();
    this.setState({ record: this.handleData(nextProps.editRecord), scope: nextProps.editRecord.scope || 'BOOKS' },() => {
      this.initForm();
    });
  }

  handleData = data => {
    let params = JSON.parse(JSON.stringify(data));
    data.itemDtos && Object.keys(data.itemDtos).map(item => {
      params[item] = [];
      data.itemDtos[item].map(it => params[item].push(it.itemCode));
    });
    return params;
  };

  initForm = () => {
    const { categoryItemCode, setOfBooksId } = this.props;
    this.setState({ loading: true });
    AllocateServices.getInitForm({ categoryItemCode, setOfBooksId }).then(res => {
      this.setState({ loading: false, extraForm: res.data.itemDtos || [] });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({ loading: false });
    });
  };

  handleChangeRange = e => {
    this.setState({ scope: e.target.value })
  };

  handleAssignCompany = data => {
    const { record } = this.state;
    let temp = [];
    data.map(item => {
      temp.push({ companyId: item.companyId, ruleId: record.ruleId });
    });
    this.setState({ assignCompanies: temp });
  };

  handleSave = () => {
    const { setOfBooksId, categoryItemCode, close } = this.props, { extraForm, record, assignCompanies } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err){
        let params = {
          setOfBooksId,
          categoryItemCode,
          scope: values.scope,
          itemDtos: {},
          finConfigGroupCompanyDtos: assignCompanies
        };
        Object.keys(extraForm).map(item => {
          let temp = [];
          if (Array.isArray(values[item])) {
            values[item].map(it => {
              temp.push({ itemCode: it, parentCode: item });
            });
          } else {
            temp.push({ itemCode: values[item], parentCode: item })
          }
          params.itemDtos[item] = temp;
        });
        record.ruleId && (params.ruleId = record.ruleId);
        this.setState({ saveLoading: true });
        AllocateServices.saveForm(params).then(() => {
          this.setState({ saveLoading: false });
          close(true);
        }).catch(e => {
          this.setState({ saveLoading: false });
        })
      }
    })
  };

  renderItem  = (type, options) => {
    let res = <div/>;
    switch (type) {
      case 'checkbox':
        res = <Group options={options} className={'item-height'}/>;
        break;
      case 'radio':
        res = <RadioGroup options={options} className={'item-height'}/>;
        break;
      default:
        break;
    }
    return res;
  };

  render() {
    const { record, rangeOptions, scope, saveLoading, loading, extraForm } = this.state,
      { initObject, setOfBooksId, categoryItemCode } = this.props,
      { getFieldDecorator } = this.props.form;
    return (
      <div>
        <Spin spinning={loading}>
          <Form style={{ marginTop: '10px' }}>
            {
              Object.keys(extraForm).map(item => {
                let options = [];
                extraForm[item].map(it => {
                  options.push({ label: it.showName, value: it.itemCode });
                });
                let title = initObject.find(it => it.columnCode === item) || {};
                return (
                  <Item label={title.columnShowName || ''} {...formItemLayout}>
                    {getFieldDecorator(item, {
                      rules: [{
                        required: true, message: messages('common.please.select')/*请选择*/,
                      }],
                      initialValue: title.columnType === 'radio' ? (record[item] ? record[item][0] : undefined) : record[item]
                    })(
                      this.renderItem(title.columnType, options)
                    )}
                  </Item>
                )
              })
            }
            <Item label={messages('setting.key2146')/*应用范围*/} {...formItemLayout}>
              {getFieldDecorator('scope', {
                rules: [{
                  required: true, message: messages('common.please.select')/*请选择*/,
                }],
                initialValue: record.scope || 'BOOKS'
              })(
                <RadioGroup options={rangeOptions} onChange={this.handleChangeRange}/>
              )}
            </Item>
            {
              scope === 'COMPANY' && (
                <Row>
                  <Col span={14} offset={8}>
                    <Item>
                      {getFieldDecorator('company', {
                        rules: [{
                          required: true, message: messages('common.please.select')/*请选择*/,
                        }],
                        initialValue: record.company
                      })(
                        <AssignCompany
                          onChange={this.handleAssignCompany}
                          ruleId={record.ruleId ? record.ruleId + '' : ''}
                          setOfBooksId={setOfBooksId}
                          categoryItemCode={categoryItemCode}
                        />
                      )}
                    </Item>
                  </Col>
                </Row>
              )
            }
          </Form>
        </Spin>
        <div className="footer-operate" style={{ backgroundColor: '#ffffff', left: '0px' }}>
          <Button type="primary" onClick={this.handleSave} style={{ margin: '0px 10px' }}
                  loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

const wrappedDataRule = Form.create()(AddDesk);
export default wrappedDataRule;
